package com.example.rabbitmqbootconsumer.config;

import com.example.rabbitmqbootconsumer.receiver.direct.AckDirectReceiver;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.example.rabbitmqbootconsumer.constant.MessageConstant.DIRECT_QUEUE_NAME;
import static com.example.rabbitmqbootconsumer.constant.MessageConstant.FANOUT_QUEUE_NAME1;

/**
 * 消息监听配置
 *
 * @author 伯路平
 * @since 2023/6/20
 **/
@Configuration
@RequiredArgsConstructor
public class MessageListenerConfig {
    private final CachingConnectionFactory cachingConnectionFactory;
    private final AckDirectReceiver ackDirectReceiver;

    @Bean
    public SimpleMessageListenerContainer getSimpleMessageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory);
        container.setConcurrentConsumers(1);
        container.setMaxConcurrentConsumers(1);
        // rabbitmq默认是自动确认，改为手动确认
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        // 可以同时设置多个队列名称，在监听的时候通过名字进行区分
        container.setQueueNames(DIRECT_QUEUE_NAME, FANOUT_QUEUE_NAME1);
        container.setMessageListener(ackDirectReceiver);
        return container;
    }
}
